package com.sprite.utils.http;

import com.sprite.utils.text.InsensitiveString;

import java.util.LinkedHashMap;
import java.util.Map;
import java.util.Set;

/**
 * @author Jack
 */
public class Headers {

    private LinkedHashMap<InsensitiveString, Object> headers = new LinkedHashMap<>();

    /**
     * 添加一个请求头
     *
     * @param headerName
     *         名称
     * @param headerValue
     *         值
     */
    public void addHeader(String headerName, Object headerValue) {
        headers.put(InsensitiveString.insensitive(headerName), headerValue);
    }

    public String getHeader(String headerName) {
        return toString(headers.get(InsensitiveString.insensitive(headerName)));
    }

    /**
     * @param headerName
     *         名称
     * @param headerValue
     *         值
     * @deprecated
     */
    public void put(String headerName, Object headerValue) {
        headers.put(InsensitiveString.insensitive(headerName), headerValue);
    }

    private String toString(Object value) {
        if (value == null) {
            return null;
        }
        return value.toString();
    }

    public int size() {
        return headers.size();
    }

    public boolean isEmpty() {
        return headers.isEmpty();
    }

    public boolean containsKey(Object key) {
        if (key instanceof String) {
            return headers.containsKey(InsensitiveString.insensitive((String) key));
        }
        return headers.containsKey(key);
    }

    public Object get(Object key) {
        if (key instanceof String) {
            return headers.get(InsensitiveString.insensitive((String) key));
        }
        return headers.get(key);
    }

    public Object remove(Object key) {
        if (key instanceof String) {
            return headers.remove(InsensitiveString.insensitive((String) key));
        }
        return headers.remove(key);
    }


    public void clear() {
        headers.clear();
    }

    public Set<InsensitiveString> keySet() {
        return headers.keySet();
    }

    public Set<Map.Entry<InsensitiveString, Object>> entrySet() {
        return headers.entrySet();
    }
}
